package com.meida.archive.admin.handler;

import com.meida.base.provider.handler.BaseAdminUserAddHandler;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.handler.BaseCheckAuthHandler;
import com.meida.common.base.service.BaseAdminUserService;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.event.FlymeEventClient;
import com.meida.module.admin.client.entity.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 后台用户添加扩展
 *
 * @author zyf
 */
@Component
public class AdminUserAddHandler extends BaseAdminUserAddHandler {


    @Resource
    private BaseAdminUserService baseAdminUserService;


    @Autowired(required = false)
    private BaseCheckAuthHandler baseCheckAuthHandler;

    @Resource
    private FlymeEventClient flymeEventClient;

    @Override
    public ResultBody validate(CriteriaSave cs, EntityMap params) {
        Long companyId = FlymeUtils.isEmpty(cs.getLong("companyId")) ? OpenHelper.getCompanyId() : cs.getLong("companyId");
        if (FlymeUtils.isNotEmpty(baseCheckAuthHandler)) {
            Long count = baseAdminUserService.countByCompanyId(companyId);
            Boolean tag= baseCheckAuthHandler.checkUserCount(count.intValue());
            if(!tag){
                return ResultBody.failed("添加失败:已达最大授权数量");
            }
        }
        return ResultBody.ok();
    }
    @Override
    public void complete(CriteriaSave cs, EntityMap params, BaseUser baseUser) {
        super.complete(cs,params,baseUser);
        //发送同步账户通知
        EntityMap map = new EntityMap();
        map.put("userId", baseUser.getUserId());
        map.put("userName", FlymeUtils.isNotEmpty(baseUser.getAccount())?baseUser.getAccount():baseUser.getUserName());
        map.put("password", baseUser.getPassword());
        map.put("optType", "add");
        flymeEventClient.pushMinioSyncUserEvent(map);
    }
}
